<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - 管理员专用</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 16px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.3);
            padding: 30px;
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
        }

        .header h1 {
            font-size: 28px;
            color: #333;
            margin-bottom: 10px;
        }

        .header p {
            color: #666;
            font-size: 14px;
        }

        .user-info {
            background: #f5f5f5;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 14px;
        }

        .user-info strong {
            color: #667eea;
        }

        .table-container {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #e0e0e0;
        }

        th {
            background: #f5f5f5;
            font-weight: 600;
            color: #333;
        }

        tr:hover {
            background: #f9f9f9;
        }

        .badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }

        .badge-super {
            background: #ff5722;
            color: white;
        }

        .badge-admin {
            background: #ff9800;
            color: white;
        }

        .badge-sub {
            background: #4caf50;
            color: white;
        }

        .btn {
            padding: 6px 16px;
            border: none;
            border-radius: 6px;
            font-size: 13px;
            cursor: pointer;
            transition: all 0.3s;
            margin-right: 5px;
        }

        .btn-promote {
            background: #2196F3;
            color: white;
        }

        .btn-promote:hover {
            background: #1976D2;
        }

        .btn-delete {
            background: #f44336;
            color: white;
        }

        .btn-delete:hover {
            background: #d32f2f;
        }

        .btn-back {
            background: #9e9e9e;
            color: white;
            padding: 10px 20px;
            margin-bottom: 20px;
        }

        .btn-back:hover {
            background: #757575;
        }

        .message {
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: none;
            font-size: 14px;
        }

        .message.success {
            background: #e8f5e9;
            color: #2e7d32;
            border: 1px solid #4caf50;
        }

        .message.error {
            background: #ffebee;
            color: #c62828;
            border: 1px solid #f44336;
        }

        .message.show {
            display: block;
        }

        .disabled {
            opacity: 0.5;
            cursor: not-allowed !important;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>👥 用户管理</h1>
            <p>管理系统所有用户</p>
        </div>

        <div class="user-info" id="currentUserInfo" style="display:none;">
            当前登录：<strong id="currentUsername"></strong> (<span id="currentUserRole"></span>)
        </div>

        <button class="btn btn-back" onclick="window.location.href='home.html'">返回首页</button>

        <div class="message" id="message"></div>

        <div class="table-container">
            <div id="loadingDiv" class="loading">加载中...</div>
            <table id="userTable" style="display:none;">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户名</th>
                        <th>角色</th>
                        <th>邮箱</th>
                        <th>手机号</th>
                        <th>登录次数</th>
                        <th>最后登录</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="userTableBody">
                </tbody>
            </table>
        </div>
    </div>

    <script>
        const API_BASE_URL = '/api/user';
        let currentUserLevel = 0;
        let currentUsername = '';

        // 页面加载时检查登录状态和权限
        window.addEventListener('DOMContentLoaded', async () => {
            await checkLoginAndPermission();
            await loadUsers();
        });

        // 检查登录状态和管理员权限
        async function checkLoginAndPermission() {
            const token = localStorage.getItem('token');
            const username = localStorage.getItem('username');
            
            if (!token || !username) {
                alert('⚠️ 请先登录');
                window.location.href = '/login.html';
                return;
            }

            try {
                const response = await fetch(`${API_BASE_URL}/validate`, {
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                });
                
                const result = await response.json();
                
                if (result.code !== 200) {
                    alert('⚠️ 登录已过期，请重新登录');
                    localStorage.clear();
                    window.location.href = '/login.html';
                    return;
                }
                
                // 获取用户级别
                const userLevel = result.data.userLevel || result.data.administrator || 0;
                currentUserLevel = parseInt(userLevel);
                currentUsername = username;
                
                // 检查是否为管理员或总管理员
                if (currentUserLevel < 1) {
                    alert('⚠️ 权限不足：只有管理员及以上级别可以管理用户');
                    window.location.href = '/home.html';
                    return;
                }
                
                // 显示当前用户信息
                document.getElementById('currentUsername').textContent = username;
                const roleText = currentUserLevel == 2 ? '总管理员' : (currentUserLevel == 1 ? '管理员' : '子管理员');
                document.getElementById('currentUserRole').textContent = roleText;
                document.getElementById('currentUserInfo').style.display = 'block';
                
            } catch (error) {
                console.error('验证失败:', error);
                alert('⚠️ 验证失败，请重新登录');
                window.location.href = '/login.html';
            }
        }

        // 加载用户列表
        async function loadUsers() {
            const token = localStorage.getItem('token');
            
            try {
                const response = await fetch(`${API_BASE_URL}/list`, {
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    displayUsers(result.data);
                } else {
                    showMessage('获取用户列表失败：' + result.message, 'error');
                    document.getElementById('loadingDiv').textContent = '加载失败';
                }
            } catch (error) {
                console.error('获取用户列表失败:', error);
                showMessage('获取用户列表失败：' + error.message, 'error');
                document.getElementById('loadingDiv').textContent = '加载失败';
            }
        }

        // 显示用户列表
        function displayUsers(users) {
            const tbody = document.getElementById('userTableBody');
            tbody.innerHTML = '';
            
            users.forEach(user => {
                const tr = document.createElement('tr');
                
                const userLevel = user.userLevel || 0;
                const roleName = user.roleName || '未知';
                
                let badgeClass = 'badge-sub';
                if (userLevel >= 2) {
                    badgeClass = 'badge-super';
                } else if (userLevel == 1) {
                    badgeClass = 'badge-admin';
                }
                
                // 判断是否可以操作
                const isSelf = user.username === currentUsername;
                const isSuperAdmin = userLevel >= 2;
                const canDelete = !isSelf && !isSuperAdmin && (currentUserLevel == 2 || (currentUserLevel == 1 && userLevel == 0));
                const canPromoteToAdmin = currentUserLevel >= 1 && userLevel == 0 && !isSelf; // 管理员和总管理员都可以提升子管理员
                const canPromoteToSuper = currentUserLevel == 2 && userLevel == 1 && !isSelf; // 只有总管理员可以提升管理员
                
                let actionButtons = '';
                if (canPromoteToAdmin) {
                    actionButtons += `<button class="btn btn-promote" onclick="promoteToAdmin('${user.username}')">提升为管理员</button>`;
                }
                if (canPromoteToSuper) {
                    actionButtons += `<button class="btn btn-promote" onclick="promoteToSuperAdmin('${user.username}')">提升为总管理员</button>`;
                }
                if (canDelete) {
                    actionButtons += `<button class="btn btn-delete" onclick="deleteUser('${user.username}')">删除</button>`;
                }
                if (!actionButtons) {
                    actionButtons = '<span style="color:#999;">-</span>';
                }
                
                const lastLogin = user.last_login_time ? new Date(user.last_login_time).toLocaleString('zh-CN') : '-';
                
                tr.innerHTML = `
                    <td>${user.id}</td>
                    <td>${user.username}</td>
                    <td><span class="badge ${badgeClass}">${roleName}</span></td>
                    <td>${user.email || '-'}</td>
                    <td>${user.phone || '-'}</td>
                    <td>${user.login_count || 0}</td>
                    <td>${lastLogin}</td>
                    <td>${actionButtons}</td>
                `;
                
                tbody.appendChild(tr);
            });
            
            document.getElementById('loadingDiv').style.display = 'none';
            document.getElementById('userTable').style.display = 'table';
        }

        // 提升子管理员为管理员
        async function promoteToAdmin(username) {
            if (!confirm(`确定要将用户"${username}"提升为管理员吗？\n\n提升后该用户可以创建和删除子管理员。`)) {
                return;
            }
            
            const token = localStorage.getItem('token');
            
            try {
                const response = await fetch(`${API_BASE_URL}/promote-admin/${username}`, {
                    method: 'PUT',
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    showMessage('✅ 提升成功！用户已成为管理员', 'success');
                    setTimeout(() => {
                        loadUsers(); // 刷新列表
                    }, 1500);
                } else {
                    showMessage('❌ ' + result.message, 'error');
                }
            } catch (error) {
                console.error('提升用户失败:', error);
                showMessage('❌ 提升用户失败：' + error.message, 'error');
            }
        }

        // 提升管理员为总管理员
        async function promoteToSuperAdmin(username) {
            if (!confirm(`确定要将用户"${username}"提升为总管理员吗？\n\n提升后该用户将拥有最高权限。`)) {
                return;
            }
            
            const token = localStorage.getItem('token');
            
            try {
                const response = await fetch(`${API_BASE_URL}/promote-super/${username}`, {
                    method: 'PUT',
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    showMessage('✅ 提升成功！用户已成为总管理员', 'success');
                    setTimeout(() => {
                        loadUsers(); // 刷新列表
                    }, 1500);
                } else {
                    showMessage('❌ ' + result.message, 'error');
                }
            } catch (error) {
                console.error('提升用户失败:', error);
                showMessage('❌ 提升用户失败：' + error.message, 'error');
            }
        }

        // 删除用户
        async function deleteUser(username) {
            if (!confirm(`确定要删除用户"${username}"吗？\n\n此操作不可恢复！`)) {
                return;
            }
            
            const token = localStorage.getItem('token');
            
            try {
                const response = await fetch(`${API_BASE_URL}/delete/${username}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    showMessage('✅ 删除成功！', 'success');
                    setTimeout(() => {
                        loadUsers(); // 刷新列表
                    }, 1500);
                } else {
                    showMessage('❌ ' + result.message, 'error');
                }
            } catch (error) {
                console.error('删除用户失败:', error);
                showMessage('❌ 删除用户失败：' + error.message, 'error');
            }
        }

        function showMessage(text, type) {
            const messageEl = document.getElementById('message');
            messageEl.textContent = text;
            messageEl.className = `message ${type} show`;
            
            if (type === 'success') {
                setTimeout(() => {
                    messageEl.classList.remove('show');
                }, 3000);
            }
        }
    </script>
</body>
</html>

